Fudel = function() { }

/**
 * 
 * @param form		Id of the form or DOM element
 * @param options	Options : {onOK : function(), debug: bool, initurl : string, onError, onSubmit, onValidationError, onInit }
 */
Fudel.Form = function(formId,options) {

	/** Form (Prototype Extended DOM element) */
	var m_form = $(formId);
	var m_form_id = formId;
	var submit_old_value;
	
	function handleOK() {
		if (options.enableOnOK) {
			enableFormElements();
		}
		if (options.onOK){
			options.onOK();
		}
		else{
			alert("Sent - OK");
		}
	}
		
	function disableFormElements() {
		if (options.debug){ alert("Disabling elements");}
		var elems = m_form.getElements();
		elems.each(function(elem) {
			if (elem.disable){
				elem.disable();}
		});
		submit_old_value = m_form.submit.value;
		//m_form.down('#submit').value = "Sending..";
		m_form.submit.value = "Sending..";
	}
	
	function enableFormElements() {
		var elems = m_form.getElements();
		elems.each(function(elem) {
			if (elem.enable){
				elem.enable();}
		});
		//m_form.down('#submit').value = submit_old_value;
		m_form.submit.value = submit_old_value;
	}
	
	function submit(event) {
		if (options.debug) { alert("Submitting"); }
		if (options.onSubmit) { options.onSubmit(); }
		Event.stop(event);
		removeErrors();
		new Form.request(m_form_id, {
			method : 'post',
			onCreate : function() {
				if (options.debug){ alert("Request completed");}
				disableFormElements();		
			},
			onComplete : function(transport) {
				var r = transport.responseText;
				if (options.debug){ alert("Response: " + r);}
				if (options.debug){ alert("Check how the elements are disabled");}
				
				if (r == "OK") {
					handleOK();
				} else {
					enableFormElements();
					if (options.debug){ alert("isJSON?:"+r.isJSON());}
					if (r.isJSON()) {
					
						var objResult = r.evalJSON();
						
						if (objResult.ERROR) {
							if (options.onError){
								options.onError(objResult);}
						} else {
							showErrors(r.evalJSON());
							if (options.onValidationError) {options.onValidationError();}
						}
						
					} else {
						if (options.onError){
							options.onError({'ERROR':'Server Side Error. Please try again later.'});}
					}
				}
			}
		 });
	}
	
	function removeErrors() {
		if (options.debug) { alert("removeErrors()"); }
		var errors = $$('#'+m_form_id+' .error');
		errors.each(function(error) {
			error.remove();
		}); 
	}
	
	function showErrors(errors) {
		if (options.debug) { alert("showErrors()"); }
		if (options.debug) { alert("form id: " + m_form_id); }
		for (var field in errors) {
			var element = $$('#'+m_form_id+' #'+field)[0];
			element.setStyle({backgroundColor: "#FDE6E6"});
			element.insert({ after: "<div class=error>"+errors[field]+"</div>"});
		}
	}
	
	/**
	 * Load initialization data (if any)
	 */
	function initData() {
		if (options.debug) alert("Initializing form");
		if (options.debug) alert("options.init = " + options.initurl);
		new Ajax.Request(options.initurl, {
			method : 'get',
			onSuccess : function(transport) {
				var r = transport.responseText;
				if (options.debug) alert(r);
				var initData = r.evalJSON();
				var elems = m_form.getElements();
				elems.each(function(elem) {
					/*This code is not needed ..
					 * if (elem.tagName.tolower() == "select") {
						for (var k = 0; k < elem.options.length; k++) {
							alert(k + " " + elem.options[k].value);
							if (elem.options[k].value == initData[elem.id]) {
								
								elem.selectedIndex = k;
							}
						}
					}*/
					//alert(elem.type.toLowerCase());
					if (elem.type.toLowerCase() == 'checkbox') {
						if (initData[elem.id] == "1" || initData[elem.id] == 'yes')
							elem.checked = true;
					}
					if (initData[elem.id]) {
						elem.value = initData[elem.id];
					}
				});
				if (options.onInit) { options.onInit(); }
			}
		});
	}
	
	/* Shows errors in an error box */
	function showErrorsBox(errors) {
		var errorsdiv = $$('#'+m_form_id+' #errors')[0];
		
		var str = "<ul>";
		for (var field in errors)
			str += "<li>" + field + " : " + errors[field] + "</li>";
		str += "</ul>";
		errorsdiv.update(str);
	}
	
	removeErrors();
	
	/*Event.observe(window, 'load', function() {
		Event.observe(m_form,'submit',submit);
	});*/
	Event.stopObserving(m_form,'submit');
	Event.observe(m_form,'submit',submit);
	
	if (options.initurl) {
		initData();
	}
}

Fudel.redirect = function(root,url) {
	//alert("redirect");
	new Ajax.Request(root+'/servlet/DummyServer', {
		method : 'get',
		onSuccess : function(transport) {
			//alert(transport.responseText);
			var server = transport.responseText;
			var serverurl = 'http://'+server+'/'+url;
			var currentUrl = window.location.href;
			if (currentUrl.startsWith("https")) { //https
				var serverurl = 'https://'+server+'/'+url;
			}
			//alert(serverurl);
			window.location.href = serverurl;
		}
	});
}

Fudel.Layout = {};

Fudel.Layout.showLoginBox = function() {

	//new Ajax.Updater('logindiv','/card/login');
	new Ajax.Request('/card/login', {
		onComplete : function(transport) {
			$('logindiv').update(transport.responseText);
			new Fudel.Form('loginform', { onOK: function() {
				//TODO: put some code here to make the window reload
				window.location = window.location;
			}});			
		}
	});
		
}